package com.yfree.activities;

import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.Context;
import android.os.Process;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

public class YActivityManager {
    private static ArrayList<YActivity> activities;

    public static ArrayList<YActivity> getActivities() {
        if (activities == null) {
            activities = new ArrayList<>();
        }
        return activities;
    }

    public static void finishApplication() {
        for (YActivity activity : YActivityManager.getActivities()) {
            if (activity != null) {
                try {
                    activity.finish();
                } catch (Exception ignored) {
                }
            }
        }
        try {
            Process.killProcess(Process.myPid());
            System.exit(0);
        } catch (Exception ignored) {
        }
    }

    public static boolean isBackground(Context context) {
        List<RunningAppProcessInfo> appProcesses = ((android.app.ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE)).getRunningAppProcesses();
        for (RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(context.getPackageName())) {
                Log.i(context.getPackageName(), "此appimportace ="
                        + appProcess.importance
                        + ",context.getClass().getName()="
                        + context.getClass().getName());
                if (appProcess.importance != RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    Log.i(context.getPackageName(), "处于后台" + appProcess.processName);
                    return true;
                } else {
                    Log.i(context.getPackageName(), "处于前台" + appProcess.processName);
                    return false;
                }
            }
        }
        return false;
    }
}
